#include "mystdio.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

//文件权限
#define DFL_MODE 0664
//刷新缓冲区的方式
#define FLUSH_NONE 1
#define FLUSH_LINE (1<<1)
#define FLUSH_ALL (1<<2)

//打开文件
myFILE* my_fopen(const char* path, const char* mode)
{
   int flag = 0;
   int fd = 0;
   if(strcmp(mode,"r")==0)
   {
        flag |= O_RDONLY;
   }
   else if(strcmp(mode, "w") == 0)
   {
        flag |= (O_CREAT | O_TRUNC | O_WRONLY);
   }
   else if(strcmp(mode, "a") == 0)
   {
        flag |= (O_CREAT | O_WRONLY | O_APPEND);
   }
   else{
       // Do nothing
   }
   if(flag & O_CREAT)
   {
       fd = open(path,flag,DFL_MODE);
   }
   else{
       fd = open(path,flag);
   }
   if(fd <0)
   {
       errno = 2;
       return NULL;
   }

   myFILE* fp = (myFILE*)malloc(sizeof(myFILE));

   if(fp == NULL)
   {
       errno = 3;
       return NULL;
   }

    fp->flag = FLUSH_LINE;
    fp->end = 0;
    fp->fileno = fd;
    return fp;
}
//写文件
int my_fwrite(const char* s, int num, myFILE* stream)
{
    //写入
    memcpy(stream->buffer+stream->end,s,num);
    stream->end += num;

    //判断是否需要刷新缓冲区
    if((stream->flag == FLUSH_LINE) && (stream->end>0) && (stream->buffer[stream->end - 1]) == '\n')
    {
        my_fflush(stream);
    }
    return num;
}
//刷新缓冲区
int my_fflush(myFILE* stream)
{
    if(stream->end > 0)
    {
        write(stream->fileno, stream->buffer, stream->end);
        stream->end = 0;
    }
    return 0;
}
//关闭文件
int my_fclose(myFILE* stream)
{
    my_fflush(stream);
    return close(stream->fileno);
}
